package com.relife.common.utils;

import com.relife.common.bean.AuthCode;
import com.relife.common.exception.CodeErrorException;
import com.relife.common.exception.CodeTimeOutException;
import com.relife.common.http.HttpUtil;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;



public class AuthCodeUtil {
	public static String CHA_CODE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	public static String NUM_CODE = "1234567890";
	public static String NUM_CHAR_CODE = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";

	/** 验证码存放 */
	public static Map<String, List<AuthCode>> codeMap = new HashMap<String, List<AuthCode>>();

	/**
	 * 获取验证码
	 * 
	 * @author WU
	 * @date 2016年9月8日 上午11:16:14
	 * @param len
	 *            验证码长度
	 * @param rands
	 *            验证码类型
	 * @param timeOut
	 *            验证码过期时间(秒)
	 */
	public static String getCode(int len, String rands, int timeOut) {
		AuthCode code = new AuthCode();
		code.setCode(getRandom(len, rands));
		String key = HttpUtil.getSession().getId();
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.SECOND, timeOut);
		code.setFailureTime(cal.getTime());
		if (codeMap.containsKey(key)) {
			codeMap.get(key).add(code);
		} else {
			List<AuthCode> list = new ArrayList<AuthCode>();
			list.add(code);
			codeMap.put(key, list);
		}
		return code.getCode();
	}

	/**
	 * 验证验证码
	 * 
	 * @author WU
	 * @date 2016年9月8日 上午11:06:50
	 */
	public static boolean authCode(String code) throws CodeErrorException, CodeTimeOutException {
		String key = HttpUtil.getSession().getId();
		if (!codeMap.containsKey(key)) {
			throw new CodeErrorException();
		}
		List<AuthCode> list = codeMap.get(key);
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).getCode().equals(code)) {
				Date date = new Date();
				if (date.after(list.get(i).getFailureTime())) {
					throw new CodeTimeOutException();
				}
				codeMap.remove(key);
				return true;
			}
		}
		throw new CodeErrorException();
	}

	/**
	 * 
	 * 获取随机数
	 * 
	 * @author WU
	 * @date 2016年9月8日 上午11:01:46
	 * @param len
	 * @param rands
	 * @return
	 */
	public static String getRandom(int len, String rands) {
		String randomStr = "";
		Random random = new Random();
		while (randomStr.length() < len) {
			int ra = random.nextInt(rands.length());
			randomStr += rands.charAt(ra);
		}
		return randomStr;
	}

}
